package com.unionftech.baselibrary.glide

import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.unionftech.baselibrary.glide.progress.ProgressManager.glideProgressInterceptor
import okhttp3.OkHttpClient
import java.io.InputStream

@GlideModule(glideName = "IGlideModule")
class AppGlideModuleIml : AppGlideModule() {
    companion object {
        /**
         * 可以修改Glide的全局配置
         */
        @JvmField
        var options: IAppGlideOptions? = null
    }

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        options?.applyOptions(context, builder)
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        val builder = OkHttpClient.Builder().glideProgressInterceptor()
        registry.replace(
            GlideUrl::class.java,
            InputStream::class.java,
            OkHttpUrlLoader.Factory(builder.build())
        )
        options?.registerComponents(context, glide, registry)
    }

    override fun isManifestParsingEnabled(): Boolean {
        return options?.isManifestParsingEnabled() ?: false
    }

    /**
     * 修改全局配置的接口
     */
    interface IAppGlideOptions {
        fun isManifestParsingEnabled(): Boolean = false
        fun applyOptions(context: Context, builder: GlideBuilder)

        fun registerComponents(context: Context, glide: Glide, registry: Registry)
    }
}